package cn.itcast.dewu.utils;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RabbitConfirmCallbackUtil {
    /*

    参数: 消息 , exchange , runtingKey
    * */
    @Autowired
    private  RabbitTemplate rabbitTemplate;
    public  void defineRabbitConfirmCallback(Object object , String exchange,String runtingKey) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString(true));
        correlationData.getFuture().addCallback(
                result2 -> {
                    if (result2.isAck()) {
                        log.info("消息发送成功,消息id为:{}",correlationData.getId());
                    }else{
                        log.error("消息发送到交换机失败,消息的id为:{},发送失败的原因为:{}"
                                ,correlationData.getId(),result2.getReason());
                        //重新发送消息
                        rabbitTemplate.convertAndSend(exchange,
                                runtingKey,object,correlationData);
                    }
                },
                ex->{
                    log.error("消息发送异常,消息的id为:{},发送失败的原因为:{}"
                            ,correlationData.getId(),ex.getMessage());
                    //重新发送消息
                    rabbitTemplate.convertAndSend(exchange,
                            runtingKey,object,correlationData);
                }
        );
        //发送消息
        rabbitTemplate.convertAndSend(exchange,
                runtingKey,object,correlationData);
    }
}
